import Vue from 'vue'
import Vuex from 'vuex'
import socket from '../socket/index'

Vue.use(Vuex)

const state = {
  connected: false,
  nickname: '', // 当前用户昵称
  nicknames: [], // 用户列表
  holder: '', // 主持人
  lines: [] // 房间中的绘图信息（记录画了多少线，怎么画的）

}

// 修改数据方法
const mutations = {
  updateNickname(state, nickname) {
    state.nickname = nickname || ''
  },
  updateNicknames(state, nicknames) {
    state.nicknames = nicknames || []
  },
  updateHolder(state, holder) {
    state.holder = holder || ''
  },
  updateLines(state, lines) {
    state.lines = lines || []
  },
  // 追加用户
  addToNicknames(state, nickname) {
    // 用户不存在再追加
    if (!state.nicknames.includes(nickname)) state.nicknames.push(nickname)
  },
  // 更新conneted状态
  updateConnected(state, flag) {
    state.connected = flag
  },
  // 画新线
  drawNewLine(state, newLine) {
    state.lines.push(newLine)
  },
  // 鼠标滑动，更新线
  updateNewLine(state, lastLine) {
    // 更新vuex中最后一项的points
    const line = state.lines[state.lines.length - 1]
    // console.log(line)
    // 此处报错，打印line为undefind
    line.points = lastLine.points
  },
  delFromNicknames(state, nickname) {
    state.nicknames = state.nicknames.filter(item => item !== nickname)
  }
}

const actions = {
  // 确认昵称已占用
  checkUserExist(context, nickname) {
    // 拿到异步操作结果，需要promise封装
    return new Promise((resolve, reject) => {
      socket.emit('check_user_exist', nickname, isExist => {
        resolve(isExist)
      })
    })
  },
  // 一进房间告诉服务器我来了
  sendUserEnter(context) {
    const nickname = localStorage.getItem('nickname')
    socket.emit('enter', nickname)
    // 进入房间将nickname设置到vuex中
    context.commit('updateNickname', nickname)
  },
  // 发送开始游戏请求
  sendStartGame(context, imageAnswer) {
    socket.emit('start_game', imageAnswer)
  },
  // 发申请结束游戏
  sendStopGame(context) {
    socket.emit('stop_game')
  },
  // 发送绘画信息
  sendDrawNewLine(context, line) {
    socket.emit('new_line', line)
    console.log(line)
  },
  // 更新绘画
  sendUpdateNewLine(context, line) {
    socket.emit('update_line', line)
    console.log(line)
  },
  sendAnswerGame(context, inputImageName) {
    socket.emit('answer_game', inputImageName)
  },
  sendUserLeave(context) {
    // 退出消息
    socket.emit('leave')
    // 退出后清空数据
    context.commit('updateNickname', '')
    localStorage.removeItem('nickname')
  }
}

const getters = {
  isGameStarted() {
    // if (state.holder) {
    //   return ture
    // } else {
    //   return false
    // }
    return !!state.holder
  },
  isGameHolder() {
    return state.nickname === state.holder
  }
}

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})
